package com.zxmr.navigate;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.zxmr.domain.component.Component;
import com.zxmr.domain.service.ComponentService;

public class XMLConfigurationLoader {

	List<URLElement> urls;
	Component component;
	
	public void load(String xml)
	{
		File inputXml=new File(xml);
		SAXReader saxReader = new SAXReader();
		try
		{
			Document document = saxReader.read(inputXml);
			Element URLS = document.getRootElement();
			
			Element el = URLS.element("Component");
			setComponent(el);
			
			@SuppressWarnings("unchecked")
			Iterator<Element> it = URLS.elementIterator("URL");
			
			while(it.hasNext())
			{
				Element e = it.next();
				if(urls == null)
				{
					urls = new ArrayList<URLElement>();
				}
				URLElement url = generateElement(e);
				if(url != null)
					urls.add(generateElement(e));
				
			}
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	private void setComponent(Element element)
	{
		if(element == null)return;
		String name = element.attributeValue("name");
		ComponentService service = new ComponentService();
		
		component = service.query(name);
		if(component == null)
		{
			System.out.println("component "+name+" is not configured in DB");
		}
	}
	private URLElement generateElement(Element element)
	{
		if(element == null)return null;
		URLElement url = new URLElement();
		Attribute valueAttribute = element.attribute("value");
		if(valueAttribute == null)return null;
		
		url.setValue(valueAttribute.getValue());
		
		Attribute classAttribute = element.attribute("class");
		if(classAttribute == null)return null;
		url.setClassPath(classAttribute.getValue());
		
		Attribute levelAttribute = element.attribute("level");
		if(levelAttribute == null)url.setLevel(URLAccessLevel.normal);
		url.setLevel(Enum.valueOf(URLAccessLevel.class, levelAttribute.getValue()));
		
		Attribute actionAttribute = element.attribute("action");
		if(actionAttribute != null)
			url.setAction(actionAttribute.getStringValue());
		
		Attribute methodAttribute = element.attribute("method");
		if(methodAttribute != null)
			url.setMethod(methodAttribute.getStringValue());
		
		return url;
	}
	public List<URLElement> getUrls() {
		return urls;
	}

	public void setUrls(List<URLElement> urls) {
		this.urls = urls;
	}

	public Component getComponent() {
		return component;
	}

	public void setComponent(Component component) {
		this.component = component;
	}
	
	
}
